<?php
/**
 * Created by 张富琼 <zfuqiong@ifreegroup.com>.
 * User: kingzcheung
 * Date: 17-10-9
 * Time: 下午3:10
 */


namespace kingzcheung\migration\command\sql;


use kingzcheung\migration\command\Sql;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument as InputArgument;

class Create extends Sql {

    protected function configure() {
        $this->setName('sql:create')
            ->setDescription('创建一个SQL迁移')
            ->addArgument('name', InputArgument::REQUIRED, '迁移文件的名称')
            ->setHelp(sprintf('%s创建一个新的迁移文件%s', PHP_EOL, PHP_EOL));
    }


    protected function execute(Input $input, Output $output) {
        $path     = $this->getPath();
        $name     = $input->getArgument('name');
        $fileName = $this->getFileName($name);

        if (!file_exists($path)) {
            if ($this->output->confirm($this->input, '是否创建迁移目录migrations/sql? [y]/n')) {
                mkdir($path, 0755, true);
            }
        }
        $path = realpath($path);
        $file = $path .DS. $fileName;
        file_put_contents($file,'-- SQL');
    }

    /**
     * 获取创建文件的文件名
     *
     * @param $name
     * @return string
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    private function getFileName($name) {
        $current = new \DateTime('now', new \DateTimeZone('UTC'));
        $dt      = $current->format('YmdHis');
        return $dt . '_' . $name . '.sql';
    }
}